
import React, { useRef, useEffect } from "react";
import "./index.less";

interface Iprops {
    children: any;
    content: string;
}

let bgdom: any = null;
let contentDom: any = null;

const Popup = (props: Iprops) => {
    const { children, content } = props;
    const refPopup = useRef<any>(null);
    function visibleChange(value: boolean) {
        bgdom.style.cssText = `display:${value ? "block" : "none"}`;
        // 显示时重新定位
        if (value) {
            let left = refPopup.current.getBoundingClientRect().left;
            let top = refPopup.current?.getBoundingClientRect().top - contentDom.clientHeight - 5;
            contentDom.style.cssText = `left: ${left}px; top: ${top}px;`;
        }
    }
    function renderPopup() {
        if (bgdom) window.document.body.removeChild(bgdom);
        bgdom = document.createElement("div");
        contentDom = document.createElement("div");
        contentDom.innerHTML = `<div class="ui-popup-content">
	         <div class="ui-popup-arrow"><span class="ui-popup-arrow-content"></span></div>
	         <div class="ui-popup-inner" role="tooltip">${content}</div></div>`;
        bgdom.className = "ui-popup-bg";
        bgdom.style.cssText = "display:none";
        //
        contentDom.className = " ui-popup ui-popup-placement-topLeft";
        //
        window.document.body.appendChild(bgdom);
        bgdom.appendChild(contentDom);
    }
    useEffect(() => {
        renderPopup();
    }, []);
    return (
        <div ref={refPopup} onMouseEnter={visibleChange.bind(this, true)} onMouseLeave={visibleChange.bind(this, false)}>
            {children}
        </div>
    );
};

export default Popup;
